package com.example.studyFile.jdknewfeatures._02_CompletableFuture_allOf;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * 
 * @Description:TODO(CompletableFuture先后调用顺序)   
 * @author: HeShengjin
 * @date:   2021年5月8日 下午1:25:53    
 * @Copyright:
 */
public class CompletableFutureTest {
	//使用自己的线程池
	//或者： import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
	//@Resource
    //ThreadPoolTaskExecutor threadPoolTaskExecutor;
    private final static ThreadPoolExecutor executorServe = new ThreadPoolExecutor(3,
            Runtime.getRuntime().availableProcessors() * 3,
            5, 
            TimeUnit.MINUTES,
            new ArrayBlockingQueue<>(1000));
    
		 public static void main(String[] args) throws InterruptedException, ExecutionException {

			    CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return "第1个耗时的任务执行完毕！【有参数】";
			    }, executorServe);

			    CompletableFuture<String> cf2 = cf1.thenApplyAsync(s -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return s + "；第2个耗时的任务执行完毕！【有参数】";
			    }, executorServe);
			    
			    CompletableFuture<String> cf3 = cf2.thenApplyAsync(s -> {
			    	try {
						TimeUnit.SECONDS.sleep(5);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
			        return s + "；第3个耗时的任务执行完毕！【有参数】";
			    }, executorServe);
			    
			    //链式调用先后顺序结束
			    System.out.println(cf3.get());

			    //不要写前面的返回值
			    cf3.thenRun(() -> {
			    	System.out.println("第3个耗时的任务执行完毕！【无参数】");
			    });
		}
}

